# -*- coding:utf-8 -*-
# --author： jingfeng 
# time: 2019/1/9

from PIL import Image
import re
from aip import AipOcr
import requests
from lxml import etree
from fake_useragent import UserAgent

UA = UserAgent()
headers = {'User-Agent': UA.random}

requests = requests.Session()


def get_words_by_image(image):
    APP_ID = "10785312"
    API_KEY = "Tcp5Qqr2Elj2illfwFh3SbuG"
    SECRET_KEY = "Hw9nYBclaImtQQzagTcQhh4Vmmvx9CAq"
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    result = client.basicGeneral(image)
    return result


def login():
    base_url = 'https://www.douban.com'

    response = requests.get(url=base_url, headers=headers)
    html = response.text

    image_url = re.findall(r'id="captcha_image" src="(.*?)"', html)[0]
    print(image_url)
    if image_url:

        captcha_id = re.findall(r'name="captcha-id" value="(.*?)"', html)[0]
        print(captcha_id)

        response = requests.get(url=image_url, headers=headers)
        content = response.content
        with open('code.jpg','wb')as f:
            f.write(content)

        image = Image.open('code.jpg')
        image.show()
        soultion = input()
        print(soultion)
        yanzheng_login(soultion, captcha_id)

    else:
        no_yanzheng_login()

    # 返回登录页面
    url = 'https://www.douban.com/'
    response = requests.get(url=url, headers=headers)
    html = response.text
    if '志鹏' in html:
        print(html)
    else:
        # login()
        pass


# 有验证码
def yanzheng_login(solution, capt_id):
    login_url = 'https://accounts.douban.com/login'

    data = {
        'source': 'index_nav',
        'redir': 'https://www.douban.com/',
        'form_email': '17635395714',
        'form_password': 'czp09270013',
        'captcha-solution': solution,
        'captcha-id': capt_id,
        'login': '登录'
    }
    response = requests.post(url=login_url, data=data, headers=headers)


# 没有验证码
def no_yanzheng_login():
    url = 'https://www.douban.com/accounts/login'

    data = {
        'source': 'index_nav',
        'form_email': '17635395714',
        'form_password': 'czp09270013'
    }

    response = requests.post(url=url, data=data, headers=headers)


login()
